package com.atguigu.chapter09;

import com.atguigu.bean.WaterSensor;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.cep.CEP;
import org.apache.flink.cep.PatternSelectFunction;
import org.apache.flink.cep.PatternStream;
import org.apache.flink.cep.PatternTimeoutFunction;
import org.apache.flink.cep.pattern.Pattern;
import org.apache.flink.cep.pattern.conditions.SimpleCondition;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.windowing.time.Time;
import org.apache.flink.util.OutputTag;

import java.time.Duration;
import java.util.List;
import java.util.Map;

/**
 * @Author lizhenchao@atguigu.cn
 * @Date 2021/7/23 11:11
 */
public class Flink06_CEP_WithIn {
    public static void main(String[] args) throws Exception {
        // 1. 先有流
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(1);
    
        SingleOutputStreamOperator<WaterSensor> waterSensorStream = env
            .readTextFile("input/sensor.txt")
            .map(new MapFunction<String, WaterSensor>() {
                @Override
                public WaterSensor map(String value) throws Exception {
                    String[] split = value.split(",");
                    return new WaterSensor(split[0],
                                           Long.parseLong(split[1]),
                                           Integer.parseInt(split[2]));
                }
            })
            .assignTimestampsAndWatermarks(
                WatermarkStrategy
                    .<WaterSensor>forBoundedOutOfOrderness(Duration.ofSeconds(5))
                    .withTimestampAssigner((element, recordTimestamp) -> element.getTs())
            );
    
        // 2. 定义规则(模式)
        Pattern<WaterSensor, WaterSensor> pattern = Pattern
            .<WaterSensor>begin("s1")
            .where(new SimpleCondition<WaterSensor>() {
                @Override
                public boolean filter(WaterSensor value) throws Exception {
                    return "sensor_1".equals(value.getId());
                }
            })
            .next("s2")
            .where(new SimpleCondition<WaterSensor>() {
                @Override
                public boolean filter(WaterSensor value) throws Exception {
                    return "sensor_2".equals(value.getId());
                }
            })
            .within(Time.seconds(2));
    
        // 3. 把模式运用在流上-> 得到一个模式流
    
        PatternStream<WaterSensor> ps = CEP.pattern(waterSensorStream, pattern);
        // 4. 从模式流中取出匹配到的数据
        SingleOutputStreamOperator result = ps
            .select(
                new OutputTag<String>("timeout") {},
                new PatternTimeoutFunction() {
                
                    @Override
                    public Object timeout(Map pattern,
                                          long timeoutTimestamp) throws Exception {
                        //  pattern 就是超时数据
                        // flink 会自动的把返回值, 放入到侧输出流中
//                        return pattern.get("s1").toString();
                        return pattern.toString();
                    }
                
                },
                new PatternSelectFunction<WaterSensor, String>() {
                    @Override
                    public String select(Map<String, List<WaterSensor>> pattern) throws Exception {
                        return pattern.toString();
                    }
                
                });
    
        result.print("result");
        
        result.getSideOutput(new OutputTag<String>("timeout") {}).print("timeout");
    
        env.execute();
    
    }
}
